import React, { lazy, ReactNode, Suspense } from 'react'
import { createBrowserRouter, Navigate, Route } from 'react-router-dom'
import { useStoreSelector } from '~/store'
interface ProtectedRouteProps {
  children: any
}
// 假设这个函数用来检查用户是否已经登录
const isAuthenticated = () => {
  // 拿到redux中的state
  const { userInfo } = useStoreSelector((state) => state.user)
  // 判断是否登录user.totoken
  return userInfo?.token
}

// 保护路由组件
const ProtectedRoute: React.FC<ProtectedRouteProps> = ({ children }) => {
  return isAuthenticated() ? children : <Navigate to='/login' />
}

// 使用lazy加载组件
const LazyHome = lazy(() => import('~/views/Home/Home'))
const LazyShare = lazy(() => import('~/views/Share/index'))
const LazyLogin = lazy(() => import('~/views/Login/Login'))

const router = createBrowserRouter([
  {
    path: '/',
    element: (
      <Suspense fallback={<div>Loading...</div>}>
        <ProtectedRoute>
          <LazyHome />
        </ProtectedRoute>
      </Suspense>
    )
  },
  {
    path: '/share',
    element: (
      <Suspense fallback={<div>Loading...</div>}>
        <ProtectedRoute>
          <LazyShare />
        </ProtectedRoute>
      </Suspense>
    )
  },
  {
    path: '/login',
    element: <LazyLogin />
  }
  // 如果需要，可以添加更多的路由配置
])

export default router
